const xlsx = require("node-xlsx");

class importData {
    constructor(param) {
        this.index = 0; //执行数量
        this.sucTotal = 0; //成功数量
        this.failTotal = 0; //失败数量
        this.failList = []; //失败序号
        this.data = param.list.data;
        this.total = param.list.data.length;
        this.tableName = param.tableName;
        this.parse = param.parse || async function () {
            return {}
        };
        this.threads = param.threads || 80;
        this.app = param.app;
        this.isEnd = false;

        this.threads = this.threads > this.total ? this.total : this.threads;
    }

    async insertData() {
        const _index = this.index;
        let result;
        this.index++;
        try {
            result = await this.app.mysql.query(`update ${this.tableName} set Inventory = (Inventory + ?) where CounterId = ?`, await this.parse(this.data[_index]));
            //result = await this.app.mysql.insert(, await this.parse(this.data[_index]));

        } catch (err) {
            result = {};
            this.app.logger.error(err);
        }

        if (result.affectedRows === 1) { //插入成功
            console.log(`成功插入条数: ${++this.sucTotal}`);
        } else {
            this.failTotal++;
            this.failList.push(_index);
        }

        if (this.index < this.total) { //继续插入数据
            this.insertData();
        } else {
            if (this.sucTotal + this.failTotal >= this.total) { //全部插入数据并返回结果
                if (!this.isEnd) {
                    console.log('插入数据完成!!!')
                    if (this.failList.length > 0) {
                        console.log(`插入插入失败对应序号:${this.failList}`);
                    }
                    this.isEnd = true;
                }
            }
        }

    }

    start() {
        for (let i = 0; i < this.threads; i++) {
            this.insertData();
        }
    }
}

module.exports.importData = function (param) {
    try {
        let list = xlsx.parse(param.file);
        delete param.file;
        param.list = list[0];
        param.app = this;

        const importdata = new importData(param);
        importdata.start();
    } catch (err) {
        console.log(`插入数据初始化错误: ${err.message}`);
    }

}